import axios from 'axios'
import { MessageBox } from 'element-ui'
import { showLoading, tryHideLoading } from './loading.js'
// import store from '../store'
// import { getToken, removeToken } from '@/utils/auth'
import Router from '@/router'
// 封装axios请求
// 创建axios实例
const service = axios.create({
  // baseURL: process.env.BASE_API, // api 的 base_url
  baseURL: process.env.DEV_API, // api 的 base_url
  timeout: 5000 // 请求超时时间
})

// request拦截器
/* service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['x-token'] = getToken() // 让每个请求携带自定义token 根据实际情况自行修改
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
) */

// 全局加载loading方法 (请求拦截器)
service.interceptors.request.use(
  config => {
    tryHideLoading() // 避免切换请求遮罩不消失，所以就先消失遮罩
    showLoading()
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// response 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    // console.log(response.data.type === 'application/vnd.ms-excel')
    if (res.resultCode !== '0000') {
      tryHideLoading()
      // 处理错误信息
    } else {
      tryHideLoading()
      return response.data
    }
  },
  error => {
    console.log('err' + error) // for debug
    tryHideLoading()
    MessageBox.alert('网络错误，请重试', '提示', {
      confirmButtonText: '确定',
      callback: action => {
        // ocation.reload()
        // window.history.go(-1)
        // removeToken()
        Router.replace({
          path: '/login'
        })
      }
    })
    return Promise.reject(error)
  }
)
export default service
